package org.firestorm.traficforecast.test;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RoadFilter {
	public static void main(String[] args) {
		removeUnuse();
	}

	public static void removeUnuse() {
		File xmlFile = new File(
				"E:\\HOC TAP\\KI 20141\\Project\\WorkSpace\\map.osm");
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		try {
			dBuilder = dbfactory.newDocumentBuilder();
			org.w3c.dom.Document doc = dBuilder.parse(xmlFile);
			NodeList nodeLists = doc.getElementsByTagName("way");
			int len = nodeLists.getLength();
			System.out.println(len);
			for (int i = 0; i < len; i++) {
				Node nNode = nodeLists.item(i);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					NodeList tagList = eElement.getElementsByTagName("tag");
					int size = tagList.getLength();
					for (int j = 0; j < size; j++) {
						String type = tagList.item(j).getAttributes()
								.getNamedItem("k").getNodeValue();
						if (type.equals("highway")) {
							String val = tagList.item(j).getAttributes()
									.getNamedItem("v").getNodeValue();
							if (checkRoad(val)) {
								tagList.item(j).getParentNode().getParentNode()
										.removeChild(nNode);
							}
						}
					}
				}
			}

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static boolean checkRoad(String road) {
		String[] type = { "motorway", "trunk", "primary", "secondary",
				"ertiary", "unclassified", "residential", "service" };

		for (int i = 0; i < 8; i++) {
			if (type[i].equalsIgnoreCase(road)) {
				return true;
			}
		}
		return false;
	}
}
